package com.jcf.springboot.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jcf.springboot.entity.sys.Menu;
import com.jcf.springboot.mapper.MenuMapper;
import com.jcf.springboot.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jjj
 * @since 2021-03-19
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

  @Autowired
  private MenuMapper menuMapper;

  public List<Menu> getChild(String id, List<Menu> all) {
    List<Menu> childList = new ArrayList<>();
    for (Menu menu : all)
    {
      if (menu.getParentId().equals(id))
      {
        childList.add(menu);
      }
    }
    for (Menu menu : childList)
    {
      menu.setChildren(getChild(menu.getId(), all));
    }
    if (childList.size() == 0)
    {
      return null;
    }
    return childList;
  }

  public List<Menu> buildTreeMenu(List<Menu> list) {
    List<Menu> menuList = new ArrayList<>();
    for (Menu menu : list)
    {
      if (menu.getParentId().equals("0"))
      {
        menuList.add(menu);
      }
    }
    for (Menu menu : menuList)
    {
      menu.setChildren(new MenuServiceImpl().getChild(menu.getId(), list));
    }
    return menuList;
  }

  @Override
  public List<String> getMenuByRole(String rid) {
    return menuMapper.selectMidByRid(rid);
  }

  @Override
  public Boolean updatePermissionByRoles(String rid, List<String> menuIds) {

    menuMapper.deletePermissByRids(rid);
      if(!ObjectUtils.isEmpty(menuIds)){
        return menuMapper.insertPermission(rid, menuIds);
      }
      return true;
  }

  @Override
  public void deleteMenu(Menu menu) {
    menuMapper.deleteMenu(menu);
  }
}
